<template>
<div></div>
</template>

<script>
import Pubsub from 'pubsub-js'
import * as esriLoader from "esri-loader";
import MapManager from "../../../core/mapManager";
export default {
    name: "iQuery",
    components: {},
    props: {},
    data() {
        return {
            mapView: null,
            iQueryActiveState: false, //当前查询状态，true为可以查询，false为不可以查询
            // popupSelectedFeature: null,
            hiddenFields: window.g.MapConfiguration.HiddenFields,
            PopupShowAttr: window.g.MapConfiguration.PopupShowAttr,
        }
    },
    methods: {
        initIquery() {
            const self = this;
            self.iQueryActiveState = true;
            // self.mapView = MapManager.getMapViewByID("mainMap");
            // self.mapView.cursor = "help";
            // let cursorOld = "help";
            esriLoader
                .loadModules([
                    "esri/core/watchUtils",
                    "esri/tasks/IdentifyTask",
                    "esri/tasks/support/IdentifyParameters",
                    "esri/geometry/geometryEngine",
                    "esri/Graphic",
                    'esri/config',
                ])
                .then(
                    ([
                        watchUtils,
                        IdentifyTask,
                        IdentifyParameters,
                        geometryEngine,
                        Graphic,
                        esriConfig
                    ]) => {
                        self.geometryEngine = geometryEngine
                        self.Graphic = Graphic;
                        // 识别流程
                        self.clickHandler = self.mapView.on("click", (e) => {
                            //本功能中，点击地图任意位置关闭底部弹框
                            Pubsub.publish("closeBottomTK")
                            if (!self.iQueryActiveState) {
                                //属性查询功能开启时不进入事件操作
                                return;
                            }
                            // if (self.popupSelectedFeature) {
                            //     self.mapView.graphics.remove(self.popupSelectedFeature);
                            //     self.popupSelectedFeature = null;
                            // }
                            this.mapView.graphics.removeAll();
                            let goIdentify = true;
                            self.mapView.hitTest(e.screenPoint).then((hitResponse) => {
                                if (hitResponse.results.length) {
                                    const getGraphic = hitResponse.results.find((hitResult) => {
                                        return (hitResult.graphic.popupTemplate || (hitResult.graphic.layer && hitResult.graphic.layer.popupTemplate) || (hitResult.graphic.layer && hitResult.graphic.layer.customPopupID));
                                    });
                                    if (getGraphic) {
                                        goIdentify = false;
                                    }
                                }
                                // 进入识别查询
                                if (goIdentify && self.mapView.map && self.mapView.map.allLayers) {
                                    let promise = [];
                                    self.mapView.map.allLayers.items.forEach((l, i) => {                                        
                                        //1、获取identifyTask查询的url地址
                                        let identifyTask = null
                                        if (l.type == "vector-tile") { //房屋检查i查询专用！！！请不要在此if内添加其它功能的代码！！！！！！！！否则，出现bug请自行处理
                                            if (l.id == "房屋检查_HouseExamination" && l.linkFeature.length > 0) {
                                                if (Array.isArray(l.linkFeature)) {
                                                    const cities = MapManager.getAdministrativeDivisions()
                                                    for (let i = 0; i < cities.length; i++) {
                                                        if (geometryEngine.within(e.mapPoint, cities[i].geometry)) {
                                                            const t = l.linkFeature.find(lf => {
                                                                return lf.name === cities[i].attributes.name
                                                            })
                                                            identifyTask = new IdentifyTask(t.url);
                                                            break
                                                        }
                                                    }
                                                    if (!identifyTask) {
                                                        console.warn(`未匹配到linkFeature`, cities)
                                                    }
                                                } else {
                                                    identifyTask = new IdentifyTask(l.linkFeature);
                                                }

                                            }
                                        } else {//矢量图层使用的一版查询
                                            if (!l.isBaseMap && l.url && ["feature", "map-image"].indexOf(l.type) != -1) {
                                                identifyTask = new IdentifyTask(l.url);
                                            }
                                        }
                                        //2、开始identifyTask查询流程
                                        if (identifyTask) {
                                            const p = new Promise((identifyResolve, reject) => {
                                                const params = new IdentifyParameters();
                                                params.tolerance = 8;
                                                params.geometry = e.mapPoint;
                                                params.width = self.mapView.width;
                                                params.height = self.mapView.height;
                                                params.returnGeometry = true;
                                                params.layerOption = "visible";
                                                params.mapExtent = self.mapView.extent;
                                                identifyTask
                                                    .execute(params)
                                                    .then((identifyResponse) => {
                                                        if (identifyResponse && identifyResponse.results && identifyResponse.results.length > 0) {
                                                            const resFeatures = [];
                                                            identifyResponse.results.forEach((iFeature) => {
                                                                iFeature.layerTitle = l.title;
                                                                resFeatures.push(iFeature);
                                                            });
                                                            identifyResolve({
                                                                type: true,
                                                                features: resFeatures,
                                                            });
                                                        } else {
                                                            identifyResolve({
                                                                type: false
                                                            });
                                                        }
                                                    })
                                                    .catch((identifyError) => {
                                                        console.error("识别出错：", identifyError);
                                                        identifyResolve({
                                                            type: false
                                                        });
                                                    });
                                            });
                                            promise.push(p);
                                        }
                                    });
                                    if (promise.length > 0) {
                                        Promise.all(promise)
                                            .then((identifyResults) => {
                                                let identifyFeatures = [];
                                                identifyResults.forEach((r) => {
                                                    if (r.type) {
                                                        r.features.forEach((f) => {
                                                            const popupContentFields = [];
                                                            for (let field in f.feature.attributes) {
                                                                if (self.hiddenFields.indexOf(field.toUpperCase()) === -1) {
                                                                    if (f.feature.attributes[field] === null || f.feature.attributes[field] === "Null") {
                                                                        f.feature.attributes[field] = "";
                                                                    }
                                                                    popupContentFields.push({
                                                                        fieldName: field,
                                                                        label: self.PopupShowAttr[field] == undefined ? field : self.PopupShowAttr[field],
                                                                    });
                                                                }
                                                            }
                                                            const g = new Graphic({
                                                                geometry: f.feature.geometry,
                                                                attributes: f.feature.attributes,
                                                                symbol: window.g.MapConfiguration.HighlightSymbol[f.feature.geometry.type],
                                                                // popupTemplate: {
                                                                //     title: "<div style='background:transparent;'>" + f.layerTitle + "</div>",
                                                                //     fieldInfos: popupContentFields,
                                                                //     actions: [{
                                                                //       id: "details",
                                                                //       className: 'esri-icon-drag-horizontal',
                                                                //       title: "详细信息",
                                                                //       attributes: f.feature.attributes,
                                                                //       geometry: f.feature.geometry,
                                                                //     }],
                                                                //     content: [{
                                                                //         type: "fields",
                                                                //         fieldInfos: popupContentFields,
                                                                //     }],
                                                                // },
                                                            });
                                                            identifyFeatures.push(g);
                                                        });
                                                    }
                                                });
                                                if (identifyFeatures.length > 0) {
                                                    // //显示属性框代码片段---cyx20231226本项目中的功能不需要popup显示属性故而屏蔽
                                                    // self.mapView.popup.open({
                                                    //     features: identifyFeatures,
                                                    //     featureMenuOpen: true,
                                                    //     // fetchFeatures: true,
                                                    //     updateLocationEnabled: true,
                                                    // });
                                                    // setTimeout(() => {
                                                    //     try {
                                                    //         var list = document.getElementById("tempClosePopBtn");
                                                    //         list.removeChild(list.childNodes[0]);
                                                    //     } catch (error) {}
                                                    //     $(".esri-popup__feature-menu-header").append(
                                                    //         " <span id='tempClosePopBtn' style='float:right;cursor: default;' class='esri-popup__icon1 esri-icon-close'></span>"
                                                    //     );
                                                    //     setTimeout(() => {
                                                    //         $("#tempClosePopBtn").on("click", function () {
                                                    //             if (self.popupSelectedFeature) {
                                                    //                 self.mapView.graphics.remove(
                                                    //                     self.popupSelectedFeature
                                                    //                 );
                                                    //                 self.popupSelectedFeature = null;
                                                    //             }
                                                    //             self.mapView.popup.visible = false;
                                                    //         });
                                                    //     }, 10);
                                                    // }, 100);
                                                    self.mapView.graphics.add(identifyFeatures[0])
                                                    //本功能中，根据属性中的房屋编码进行搜索查询功能
                                                    Pubsub.publish("mapPopupFeature", identifyFeatures[0])
                                                }else{
                                                    self.$message({
                                                        message: "未查询到相关地块...",
                                                        type: "info",
                                                    });
                                                }
                                            })
                                            .catch((identifyResultsError) => {
                                                console.error(identifyResultsError);
                                            });
                                    } else {
                                    }
                                } else {
                                }
                            });
                        });
                    }
                )
                .catch((e) => {
                    console.error("初始化地图出错——");
                    console.error(e);
                });
        },
        closeIquery() {
            $("#tempClosePopBtn").click();
            this.mapView.cursor = "default";
            if (this.clickHandler) {
                this.clickHandler.remove();
                this.clickHandler = undefined;
            }
            if (this.popupVisibleWatcher) {
                this.popupVisibleWatcher.remove();
                this.popupVisibleWatcher = undefined;
            }
            if (this.popupSelectedFeautureWatcher) {
                this.popupSelectedFeautureWatcher.remove();
                this.popupSelectedFeautureWatcher = undefined;
            }
            this.mapView.graphics.removeAll();
            // if (this.popupSelectedFeature) {
            //     this.mapView.graphics.remove(this.popupSelectedFeature);
            //     this.popupSelectedFeature = null;
            // }
        }
    },
    watch:{
        iQueryActiveState(){
            if(this.iQueryActiveState == false){
                //清除相关信息
                Pubsub.publish("clearIQuqry");
            }
        },
    },
    mounted() {
        const self = this
        self.openIQuqryHander = Pubsub.subscribe("openIQuqry",(msg, data)=>{
            this.iQueryActiveState = true
        })
        MapManager.getMapViewByIDAsy("mainMap").then((mapView) => {
            self.mapView = mapView;
            self.closeIquery()
            self.initIquery()
        })
    },
    beforeDestroy() {
        this.closeIquery();
    }
}
</script>

<style>
</style>
